package com.kinghunt.misp.common.utils;

import com.bygoodtech.kings.common.dto.ApiResult;
import com.bygoodtech.kings.common.enums.ResultCode;
import com.kinghunt.misp.common.dto.userx.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Objects;
import java.util.Random;

/**
 * 文件上传工具类
 */
@Slf4j
public class UploadUtils {
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMddHHmmss");

    public ApiResult<String> uploadFile(UserDTO loginUser, MultipartFile file, HttpServletRequest request, String realPath) {
        //文件存放的目录
        File folder = new File(realPath);
        if (!folder.isDirectory()) {
            boolean mkdirSuccess = folder.mkdirs();
            if (!mkdirSuccess) {
                log.error("uploadImg mkdir fail, {}-{}", loginUser.getId(), folder.getAbsolutePath());
                return ApiResult.failOfCode(String.valueOf(ResultCode.ERROR_SERVER_EXCEPTION));
            }
        }
        String fileName = file.getOriginalFilename();
        try {
            File targetFile = new File(folder, fileName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            } else {
                targetFile.delete();
            }
            file.transferTo(targetFile);
        } catch (IOException e) {
            log.error("upload eBook exception, {}", loginUser.getId(), e);
            return ApiResult.failOfCode(String.valueOf(ResultCode.ERROR_SERVER_EXCEPTION));
        }
        return ApiResult.ok(fileName);
    }

    public static ApiResult<String> uploadImage(UserDTO loginUser, MultipartFile file, HttpServletRequest request, String realPath) {
        //文件存放的目录
        File folder = new File(realPath);
        if (!folder.isDirectory()) {
            boolean mkdirSuccess = folder.mkdirs();
            if (!mkdirSuccess) {
                log.error("uploadImg mkdir fail, {}-{}", loginUser.getId(), folder.getAbsolutePath());
                return ApiResult.failOfCode(String.valueOf(ResultCode.ERROR_SERVER_EXCEPTION));
            }
        }
        String oldName = file.getOriginalFilename();

        //文件后缀
        String suffix = Objects.isNull(oldName) ? ".jpg" : oldName.substring(oldName.lastIndexOf("."));
        //文件新名字
        String newName = getRandomFileName();
        String fullName = newName + suffix;
        try {
            File targetFile = new File(folder, fullName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            } else {
                targetFile.delete();
            }
            file.transferTo(targetFile);
        } catch (IOException e) {
            log.error("uploadImg exception, {}", loginUser.getId(), e);
            return ApiResult.failOfCode(String.valueOf(ResultCode.ERROR_SERVER_EXCEPTION));
        }
        return ApiResult.ok(fullName);
    }

    /**
     * 获取随机文件名 ： 时间 + 随机字符
     *
     * @return
     */
    private static String getRandomFileName() {
        StringBuilder sb = new StringBuilder();
        Calendar calendar = Calendar.getInstance();
        String createTime = SDF.format(calendar.getTime());
        sb.append(createTime);

        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            // 可以根据需要调整字符范围
            int randomChar = random.nextInt(26) + 'a';
            sb.append((char) randomChar);
        }
        return sb.toString();
    }
}
